package com.nondo.rdp.finance.endpoint.api.admin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.nondo.rdp.auth.common.RoleUtils;
import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.ConvertCall;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.auth.endpoint.model.Query;
import com.nondo.rdp.core.common.AliyunVideoTool;
import com.nondo.rdp.core.common.BeanUtils;
import com.nondo.rdp.core.common.CommUtil;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.model.AttachBean;
import com.nondo.rdp.core.model.Video;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.domain.course.Section;
import com.nondo.rdp.finance.domain.course.SectionComment;
import com.nondo.rdp.finance.model.course.SectionBean;
import com.nondo.rdp.finance.model.course.SectionCommentBean;
import com.nondo.rdp.finance.model.course.SectionEdit;
import com.nondo.rdp.finance.model.course.SectionQuery;
import com.nondo.rdp.finance.service.course.CourseBuyService;
import com.nondo.rdp.finance.service.course.CourseService;
import com.nondo.rdp.finance.service.course.SectionCommentService;
import com.nondo.rdp.finance.service.course.SectionService;

@RestController("apiAdminSection")
@RequestMapping("/api/admin/section")
public class SectionEndpoint {

    @Autowired
    CommUtil commUtil;

    @Autowired
    AliyunVideoTool aliyunVideoTool;

    @Autowired
    SectionService sectionService;

    @Autowired
    CourseService courseService;

    @Autowired
    CourseBuyService courseBuyService;

    @Autowired
    SectionCommentService sectionCommentService;

    @RequestMapping("/info/{id}")
    public View<SectionBean> info(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View<SectionBean> view = new View<SectionBean>(20000, "获取数据成功");

        Section section = null;
        SectionBean sectionBean = new SectionBean();
        if (id != null) {
            User user = UserUtils.getUser(request, response);
            section = sectionService.findOne(id);

            if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)) {
                if (!user.getId().equals(section.getPublisher().getId())) {
                    return View.ofError("对不起，你没有权限进行操作");
                }
            }
            // 更新课节信息
            section.setReadNum(section.getReadNum() + 1);
            this.sectionService.update(section);
           
			// 返回课节详情
			sectionBean = sectionService.getSectionDetail(section);
            AttachBean attachBean = sectionBean.getAttach();
            if (attachBean.getType() == 1) {
                attachBean.setPath(commUtil.getAudioUrl(attachBean.getPath()));
                sectionBean.setAttach(attachBean);
            }
        }

        view.setData(sectionBean);

        return view;
    }

    @RequestMapping("/list")
    public View<Page<SectionQuery>> list(HttpServletRequest request, HttpServletResponse response, @RequestBody Query<Section> query) {
        View<Page<SectionQuery>> view = new View<Page<SectionQuery>>(20000, "获取列表成功");

        Section section = query.getData();
        User user = UserUtils.getUser(request, response);

        if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)) {
            if (section == null) {
                section = new Section();
            }
            //课程发布者只能查询自己发布的课程
            section.setPublisher(user);
        }

        Page<Section> page = sectionService.findAll(new Page<Section>(query.getPage(), query.getSize()), section);

        Page<SectionQuery> resultPage = page.convertPage(new ConvertCall<Section, Page<SectionQuery>>() {

            @Override
            public Page<SectionQuery> execute(Page<Section> srcPage) {
                Page<SectionQuery> sectionQueryListPage = new Page<SectionQuery>(srcPage.getPageNumber(), srcPage.getPageSize(), srcPage.getTotalPages(), srcPage.getTotalElements());
                List<Section> sectionList = srcPage.getContent();
                List<SectionQuery> sectionQueryList = new ArrayList<SectionQuery>();
                for (Section section : sectionList) {
                    SectionQuery sectionQuery = SectionQuery.covert2Bean(section);
                    sectionQueryList.add(sectionQuery);
                }
                sectionQueryListPage.setContent(sectionQueryList);
                return sectionQueryListPage;
            }

        });

        view.setData(resultPage);

        return view;
    }

    @RequestMapping("/add")
    public View add(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody Section section, BindingResult result) {
        View view = new View(20000, "添加成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            User user = UserUtils.getUser(request, response);
            Course course = this.courseService.findOne(section.getCourseId());
            if (course == null) {
                return View.ofError("所属课程不存在");
            }
            if (!course.getUser().getId().equals(user.getId())) {
                return View.ofError("对不起，你没有权限进行操作");
            }
			if (course.getType() == 1) {
				List<Section> sectionList = null;
				sectionList = this.sectionService.findByCourseId(section.getCourseId());
				if (sectionList != null && sectionList.size() > 0) {
					return View.ofError("对不起，普通课程只能添加一节课");
				}
			}
            section.setCourse(course);
            section.setPublisher(user);
            this.sectionService.save(section);
        }
        return view;
    }

    @RequestMapping("/update")
    public View update(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody SectionEdit section, BindingResult result) {
        View view = new View(20000, "更新成功");

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            User user = UserUtils.getUser(request, response);
            Section sectionDb = this.sectionService.findOne(section.getId());
            if (!user.getId().equals(sectionDb.getPublisher().getId())) {
                return View.ofError("对不起，你没有权限进行操作");
            }
            BeanUtils.copy(section, sectionDb);
            this.sectionService.updateAdmin(sectionDb);
        }

        return view;
    }

    @RequestMapping("/delete/{id}")
    public View delete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");
        User user = UserUtils.getUser(request, response);
        Section section = this.sectionService.findOne(id);
        if (RoleUtils.hasRole(Collections.singletonList(user.getRole()),
                RoleUtils.GENERAL)
                && !user.getId().equals(section.getPublisher().getId())) {
            return View.ofError("对不起，你没有权限进行操作");
        }
        this.sectionService.delete(id);
        return view;
    }

    @RequestMapping("/comment")
    public View<SectionCommentBean> comment(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody SectionCommentBean sectionComment) {
        View<SectionCommentBean> view = new View<SectionCommentBean>(20000, "评论成功");
        User user = UserUtils.getUser(request, response);
        SectionComment comment = new SectionComment();
        BeanUtils.copy(sectionComment, comment);
        Section section = this.sectionService.findOne(sectionComment.getSectionId());
        comment.setUser(user);
        comment.setSection(section);
        this.sectionCommentService.save(comment);
        sectionComment = SectionCommentBean.covert2Bean(comment);
        view.setData(sectionComment);
        return view;
    }

    @RequestMapping("/author/comment")
    public View<SectionCommentBean> authorComment(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody SectionCommentBean sectionComment) {
        View<SectionCommentBean> view = new View<SectionCommentBean>(20000, "评论成功");
        User user = UserUtils.getUser(request, response);
        SectionComment comment = this.sectionCommentService.findOne(sectionComment.getId());
        if (!user.getId().equals(comment.getSection().getPublisher().getId())) {
            return View.ofError("对不起，你没有权限进行操作");
        }
        comment.setAuthorCommentDate(new Date());
        comment.setAuthorComment(sectionComment.getAuthorComment());
        this.sectionCommentService.update(comment);
        sectionComment = SectionCommentBean.covert2Bean(comment);
        view.setData(sectionComment);
        return view;
    }

    @RequestMapping("/comment/delete/{id}")
    public View commentDelete(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) {
        View view = new View(20000, "删除成功");
        User user = UserUtils.getUser(request, response);
        SectionComment comment = this.sectionCommentService.findOne(id);
        if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)) {
            if (!user.getId().equals(comment.getSection().getPublisher().getId())) {
                return View.ofError("对不起，你没有权限进行操作");
            }
        }
        this.sectionCommentService.delete(id);
        return view;
    }

    @RequestMapping("/comment/audit")
    public View commentAudit(HttpServletRequest request, HttpServletResponse response, @RequestBody SectionComment sectionComment) {
        View view = new View(20000, "审核成功");
        User user = UserUtils.getUser(request, response);
        SectionComment comment = this.sectionCommentService.findOne(sectionComment.getId());
        if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)) {
            if (!user.getId().equals(comment.getSection().getPublisher().getId())) {
                return View.ofError("对不起，你没有权限进行操作");
            }
        }
        sectionComment.setAuditStatus(sectionComment.getAuditStatus());
        this.sectionCommentService.update(sectionComment);
        return view;
    }

    @RequestMapping(value = "/play/auth")
    public View<GetVideoPlayAuthResponse> playAuth(HttpServletRequest request,
                                                   HttpServletResponse response, @RequestBody Video video, BindingResult result) {
        View<GetVideoPlayAuthResponse> view = new View<GetVideoPlayAuthResponse>(
                20000, "授权成功");
        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
            return view;
        }
        User user = UserUtils.getUser(request, response);
        if (RoleUtils.hasRole(Collections.singletonList(user.getRole()), RoleUtils.GENERAL)) {
            Section section = sectionService.findOne(video.getSid());
            Course course = section.getCourse();

            int isFree = course.getFree();
            if (isFree == 0) {
                int isBuy = courseBuyService.getOne(course.getId(), user.getId());
                if (isBuy == 0) {
                    view.setCode(30000);
                    view.setMessage("对不起，你没有购买该课程");
                    return view;
                }
                if (!video.getVideoId().equals(section.getAttach().getVideoId())) {
                    return View.ofError("对不起，购买的课程ID和视频ID不匹配");
                }
            }
        }
        try {
            GetVideoPlayAuthResponse authResponse = aliyunVideoTool
                    .getVideoPlayAuth(video.getVideoId());
            view.setData(authResponse);
        } catch (ClientException e) {
            return View.ofError("获取播放凭证失败");
        }
        return view;
    }

}
